package user

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"project-im/config"
	"project-im/internal/api/request"
	"project-im/internal/api/response"
	"project-im/internal/model/dao"
	"project-im/internal/model/service"
	"project-im/tools"
	"time"
)

func Login(c *gin.Context) {
	var json request.Logins
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	userName := json.UserName
	password := json.Password

	//判断用户是否已经注册 通过用户名
	if service.IsRegister(userName) == false {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该用户不存在"})
		return
	}
	//判断用户状态是否被封禁
	if service.IsBanned(userName) == false {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该用户已被封禁"})
		return
	}
	//判断密码是否正确
	var user dao.ImUser
	config.DB.Where("user_name=?", userName).First(&user)
	if user.Password != password {
		c.JSON(http.StatusBadRequest, gin.H{"error": "密码错误"})
		return
	}
	//设置session
	session := request.LoginSession{
		UserId:   user.ID,
		Terminal: json.Terminal,
	}
	//生成token
	jwtSign := tools.NewJWT(config.AppConfig.Jwt.Key)
	jwtClaims := tools.CustomClaims{
		ID:      user.ID,
		Session: session,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + config.AppConfig.Jwt.Expiry,
		},
	}
	token, err := jwtSign.CreateToken(jwtClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "token生成失败"})
		return
	}
	refreshToken, err := jwtSign.CreateToken(jwtClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "refreshToken生成失败"})
		return
	}
	data := response.LoginResponse{
		AccessToken:           token,
		AccessTokenExpiresIn:  config.AppConfig.Jwt.Expiry,
		RefreshToken:          refreshToken,
		RefreshTokenExpiresIn: config.AppConfig.Jwt.Expiry,
	}
	//登录成功
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    data,
	})
}
